package cn.oowoo.jsr303.common.util;

import cn.oowoo.jsr303.common.dto.JSR303TestDto;
import cn.oowoo.jsr303.common.result.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.*;

@Slf4j
public class ValidateUtil {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static Result validate(BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            List<String> errorResult = new ArrayList<>();
            allErrors.forEach(x->{
                FieldError error = (FieldError)x;
                String err =   error.getField() + " : " + error.getDefaultMessage();
                log.info(err);
                errorResult.add(err);
            });
            return Result.fail(JSON.toJSONString(errorResult));
        }
        return null;
    }

    /**
     * @Author: zhangbin
     * @Date: 2019/6/17 18:04
     * @Return
     * @Description:用于封装Hibernate Validator
     * 
     */
    public static <T> Map<String,StringBuffer> validate(T obj){
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        Map<String,StringBuffer> errorMap = null;
        if(set != null && set.size() >0 ){
            errorMap = new HashMap<>();
            String property = null;
            for(ConstraintViolation<T> cv : set){
                property = cv.getPropertyPath().toString();
                if(errorMap.get(property) != null){
                    errorMap.get(property).append("," + cv.getMessage());
                }else{
                    StringBuffer sb = new StringBuffer();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }
        return errorMap;
    }
    public static void main(String[] args) {
        JSR303TestDto jsr303TestDto = new JSR303TestDto();
        jsr303TestDto.setId(null);
        jsr303TestDto.setName("");
        jsr303TestDto.setAge(201);
        jsr303TestDto.setSex(3);
        jsr303TestDto.setPhone("123123");
        jsr303TestDto.setEmail("4515dasd");
        jsr303TestDto.setFavorites(Arrays.asList("篮球"));
        jsr303TestDto.setEnable(2);
        Map<String, StringBuffer> validateRes = ValidateUtil.validate(jsr303TestDto);
        validateRes.forEach((k,v)->{
            System.out.println(k+" -> "+v);
        });
    }
}
